export default {
  props: {
    ListLength: {
      type: Number,
      default: 6
    }
  },
  data() {
    return {
      blockList: [],
      lastHeight: 0
    };
  },
  computed: {
    maxHeight() {
      return this.$store.state.maxHeight || 0;
    }
  },
  watch: {
    maxHeight(height) {
      this.checkNewBlock(height)
    }
  },
  mounted() {
    this.init()
    this.checkNewBlock()
  },
  methods: {
    init() {
      if (this.blockList.length === 0) {
        let max = this.ListLength
        let initBlock = {
          height: '',
          minerHash: '',
          txs: [],
          blockTime: ''
        }
        while (max > 0) {
          this.blockList.push(initBlock)
          max--
        }
      } else return
    },
    getBlocks(start, end) {
      let list = []
      this.Rpc.getBlocks(start, end, true).then(res => {
        if (res.error === null) {
          res.result.items.forEach((item, index) => {
            list[index] = item.block
            list[index].minerHash = item.block.txs[0].from
          })
          this.blockList = list.reverse()
        }
      })
    },
    // 校验最新高度
    checkNewBlock(height) {
      let start = 0
      let end = 0
      if (this.lastHeight === 0) {
        this.getBlocks(this.maxHeight - this.ListLength + 1, this.maxHeight)
        return
      }
      if (height > this.lastHeight) {
        end = height
        start = end - this.ListLength + 1
        this.getBlocks(start, end)
      } else return
    }
  }
};